package com.yctan.base.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.yctan.base.exception.FinalCode;

import java.io.Serializable;
import java.util.HashMap;

@JsonIgnoreProperties(ignoreUnknown=true)
@JsonInclude(Include.NON_NULL)
public class WebResult extends HashMap<String, Object> implements Serializable {
	
	private static final long serialVersionUID = -1581392669077986558L;
	
	//状态码KEY
	public static final String PARAM_CODE = "code";
	//结果KEY
	public static final String PARAM_DATA = "data";
	//信息KEY
	public static final String PARAM_MSG = "msg";

	
	/**
	 * 重写HashMap.put方法
	 * 过滤put关键字为code、data、msg的操作
	 */
	@Override
	public Object put(String key, Object value) {
		if (null == key) { return value; }
		switch (key) {
		case PARAM_CODE : 
		case PARAM_DATA : 
		case PARAM_MSG : 
			return value;
		default : 
			return super.put(key, value);
		}
    }
	
	public int getCode() {
		Object codeObject = this.get(PARAM_CODE);
		return null == codeObject ? null : Integer.parseInt(codeObject.toString());
	}
	public void setCode(int code) {
		super.put(PARAM_CODE, code);
	}
	public WebResult code(int code) {
		this.setCode(code);
		return this;
	}

	public Object getData() {
		return this.get(PARAM_DATA);
	}
	public void setData(Object data) {
		super.put(PARAM_DATA, data);
	}
	public WebResult data(Object data) {
		this.setData(data);
		return this;
	}

	public String getMsg() {
		Object msgObj = this.get(PARAM_MSG);
		return null == msgObj ? null : msgObj.toString();
	}
	public void setMsg(String msg) {
		super.put(PARAM_MSG, msg);
	}
	public WebResult msg(String msg) {
		this.setMsg(msg);
		return this;
	}

	public WebResult success(Object data) {
		return this.data(data)
			.msg("请求成功!")
			.code(FinalCode.REQUEST_SUCCESS);
	}
	
	public WebResult failed(String msg) {
		return this.msg(msg)
			.code(FinalCode.REQUEST_FAILED);
	}
	
}
